package com.msteam.tools.report.helper;

import com.msteam.tools.code.generator.GenException;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import static com.jfinal.core.Const.DEFAULT_ENCODING;

public class ReportHelper {
	private Configuration configuration = null;
	private static String TEMPLATE_DIR = "";
	private Map<String,Object> tempData = new HashMap<String,Object>();
	
	
    public ReportHelper(String templatesBaseDir) {
        configuration = new Configuration(Configuration.VERSION_2_3_21);
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassicCompatible(true);
        TEMPLATE_DIR = templatesBaseDir;
        
    }
    public String RenderTemplateFile(String templateFilename){
    	 TemplateLoader loader;
         try {
             loader = new FileTemplateLoader(new File(TEMPLATE_DIR));
         } catch (IOException e) {
             throw new GenException(e);
         }
        configuration.setTemplateLoader(loader);
        try {
			Template temp = configuration.getTemplate(templateFilename, DEFAULT_ENCODING);
			
			Writer out = new StringWriter(4096000);
	        temp.process(tempData, out);
	        System.out.println(out.toString());
	        return out.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
        
    	return "";
    }
    
    public String RenderText(String templateContent){
    	StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("myTemplate", templateContent);
        configuration.setTemplateLoader(stringLoader);
        try {
			Template temp = configuration.getTemplate("myTemplate","utf-8");
			
			Writer out = new StringWriter(4096000);
	        temp.process(tempData, out);
	        //System.out.println(out.toString());
	        return out.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
        
    	return "";
    }
    /**
     * 清空
     */
    public void clear(){
    	tempData =  new HashMap<String,Object>();
    }
    public void putAll(Map<String, Object> map) {
        for (String key : map.keySet()) {
        	put(key, map.get(key));
        }
    }
	public void put(String key, Object value){
		if(tempData.containsKey(key)){
			tempData.remove(key);
		}
		tempData.put(key, value);
	}
}
